<template>
  <!-- 添加数据相关 -->
  <!-- 是否添加数据的按钮 -->
  <div class="button-group">
    <el-button type="primary" @click="toggleForm">添加或更新数据</el-button>
    <div class="filter-buttons">
      <el-button
        :type="currentFilter === 'all' ? 'primary' : 'default'"
        @click="filterData('all')"
      >
        显示所有数据
      </el-button>
      <el-button
        :type="currentFilter === 'pending' ? 'primary' : 'default'"
        @click="filterData('pending')"
      >
        待审核数据
      </el-button>
      <el-button
        :type="currentFilter === 'reviewed' ? 'primary' : 'default'"
        @click="filterData('reviewed')"
      >
        已审核数据
      </el-button>
    </div>
  </div>
  <div class="data-add" v-show="showForm">
    <!-- 登记编号 -->
    <el-form-item label="登记编号">
      <el-input v-model="formData.uuid" placeholder="请输入登记编号" />
    </el-form-item>

    <!-- 用户提问 -->
    <el-form-item label="用户提问">
      <el-input
        v-model="formData.question"
        type="textarea"
        :rows="4"
        placeholder="请输入用户提问"
      />
    </el-form-item>

    <!-- 机器人回答 -->
    <el-form-item label="机器人回答">
      <el-input
        v-model="formData.answer"
        type="textarea"
        :rows="4"
        placeholder="请输入机器人回答"
      />
    </el-form-item>

    <!-- 数据来源 -->
    <el-form-item label="数据来源">
      <el-select v-model="formData.dataSource" placeholder="请选择数据来源">
        <el-option label="用户手册" value="用户手册" />
        <el-option label="蓝皮书" value="蓝皮书" />
        <el-option label="机器生成" value="机器生成" />
      </el-select>
    </el-form-item>

    <!-- 时间选择 -->
    <el-form-item label="审核时间">
      <el-date-picker
        v-model="formData.auditTime"
        type="date"
        placeholder="选择日期"
        format="YYYY-MM-DD"
        value-format="YYYY-MM-DD"
      />
    </el-form-item>

    <!-- 审核员用户名和昵称 -->
    <el-form-item label="审核员用户名">
      <el-input v-model="formData.auditUser" placeholder="审核员用户名" />
    </el-form-item>

    <el-form-item label="审核员昵称">
      <el-input v-model="formData.auditUserName" placeholder="审核员昵称" />
    </el-form-item>

    <!-- 三个机器人选择 -->
    <el-form-item label="标注机器人">
      <el-select
        v-model="formData.annotationRobot"
        placeholder="请选择标注机器人"
      >
        <el-option label="标注机器人一号" value="标注机器人一号" />
        <el-option label="标注机器人二号" value="标注机器人二号" />
        <el-option label="标注机器人三号" value="标注机器人三号" />
      </el-select>
    </el-form-item>

    <el-form-item label="审核机器人">
      <el-select v-model="formData.auditRobot" placeholder="请选择审核机器人">
        <el-option label="审核机器人一号" value="审核机器人一号" />
        <el-option label="审核机器人二号" value="审核机器人二号" />
        <el-option label="审核机器人三号" value="审核机器人三号" />
      </el-select>
    </el-form-item>

    <el-form-item label="评估机器人">
      <el-select v-model="formData.assessRobot" placeholder="请选择评估机器人">
        <el-option label="评估机器人一号" value="评估机器人一号" />
        <el-option label="评估机器人二号" value="评估机器人二号" />
        <el-option label="评估机器人三号" value="评估机器人三号" />
      </el-select>
    </el-form-item>

    <!-- 审核结果按钮组 -->
    <el-form-item label="审核结果">
      <el-radio-group v-model="formData.peopleAuditResult">
        <el-radio-button type="success" label="人工审核通过"
          >通过</el-radio-button
        >
        <el-radio-button type="danger" label="人工审核不通过"
          >不通过</el-radio-button
        >
        <el-radio-button type="warning" label="待审核">待审核</el-radio-button>
      </el-radio-group>
    </el-form-item>

    <!-- 评估参考文档 -->
    <el-form-item label="评估参考文档">
      <el-select
        v-model="formData.referenceDoc"
        placeholder="请选择评估参考文档"
      >
        <el-option label="评估手册" value="评估手册" />
        <el-option label="AI评估问答" value="AI评估问答" />
      </el-select>
    </el-form-item>

    <!-- 添加确定按钮 -->
    <el-form-item>
      <el-button type="primary" @click="handleAdd">确定添加</el-button>
      <el-button type="primary" @click="handleUpdate">确定更新</el-button>
    </el-form-item>
  </div>

  <!-- 数据展示，允许用户编辑与更新 -->
  <div class="data-overview">
    <el-table
      :data="filteredTableData"
      style="width: 100%"
      v-loading="loading"
      size="small"
    >
      <el-table-column
        prop="question"
        label="用户提问"
        min-width="200"
        show-overflow-tooltip
      >
        <template #default="scope">
          <div v-if="scope.row.isEditingQuestion" class="edit-cell">
            <el-input
              v-model="scope.row.question"
              type="textarea"
              :rows="4"
              @blur="confirmEdit(scope.row, 'question')"
              @keyup.enter.prevent="$event.target.blur()"
              v-focus
              resize="none"
            />
          </div>
          <div
            v-else
            class="ellipsis-cell clickable"
            @click="startEdit(scope.row, 'question')"
          >
            {{ scope.row.question }}
          </div>
        </template>
      </el-table-column>
      <el-table-column
        prop="answer"
        label="机器人回答"
        min-width="200"
        show-overflow-tooltip
      >
        <template #default="scope">
          <div v-if="scope.row.isEditingAnswer" class="edit-cell">
            <el-input
              v-model="scope.row.answer"
              type="textarea"
              :rows="10"
              @blur="confirmEdit(scope.row, 'answer')"
              @keyup.enter.prevent="$event.target.blur()"
              v-focus
              resize="none"
            />
          </div>
          <div
            v-else
            class="ellipsis-cell clickable"
            @click="startEdit(scope.row, 'answer')"
          >
            {{ scope.row.answer }}
          </div>
        </template>
      </el-table-column>
      <el-table-column prop="dataSource" label="数据来源" min-width="80" />
      <el-table-column prop="auditUserName" label="人类审核员" min-width="80" />
      <el-table-column prop="annotationRobot" label="标注机器人" min-width="80" />
      <el-table-column prop="auditRobot" label="审核机器人" min-width="80" />
      <el-table-column prop="assessRobot" label="评估机器人" min-width="80" />
      <el-table-column
        prop="peopleAuditResult"
        label="是否审核通过"
        min-width="50"
      />
      <el-table-column prop="referenceDoc" label="参考文档" min-width="100" />
      <el-table-column label="操作" width="200" fixed="right">
        <template #default="scope">
          <div class="button-container">
            <div class="button-row">
              <el-button
                size="small"
                type="primary"
                @click="handleEdit(scope.row)"
              >
                修改
              </el-button>
              <el-button
                size="small"
                type="danger"
                @click="handleDelete(scope.row)"
              >
                删除
              </el-button>
            </div>
            <div class="button-row">
              <el-button
                size="small"
                type="success"
                @click="handleAudit(scope.row, '审核通过')"
              >
                审核通过
              </el-button>
              <el-button
                size="small"
                type="warning"
                @click="handleAudit(scope.row, '审核不通过')"
              >
                审核不通过
              </el-button>
            </div>
          </div>
        </template>
      </el-table-column>
    </el-table>
  </div>
</template>

<script setup>
import { ref, onMounted, nextTick } from "vue";
import axios from "axios";
import { ElMessage, ElMessageBox } from "element-plus";

//获取所有数据
const tableData = ref([]);
const loading = ref(false);

const currentFilter = ref("all"); // 当前筛选状态
const filteredTableData = ref([]); // 筛选后的数据

const fetchData = async () => {
  loading.value = true;
  try {
    const token = localStorage.getItem("token"); // 从localStorage获取token
    const response = await axios.get(
      "http://1.14.10.129:8081/system/annotation/list",
      {
        headers: {
          Authorization: token,
        },
      }
    );
    tableData.value = response.data.rows;
    applyFilter(currentFilter.value); // 获取数据后应用筛选
  } catch (error) {
    ElMessage.error("获取数据失败：" + error.message);
  } finally {
    loading.value = false;
  }
};

// 添加筛选函数
const filterData = (filterType) => {
  currentFilter.value = filterType;
  applyFilter(filterType);
};

const applyFilter = (filterType) => {
  switch (filterType) {
    case "pending":
      filteredTableData.value = tableData.value.filter(
        (row) => row.peopleAuditResult === "待审核"
      );
      break;
    case "reviewed":
      filteredTableData.value = tableData.value.filter(
        (row) => row.peopleAuditResult !== "待审核"
      );
      break;
    default:
      filteredTableData.value = tableData.value;
  }
};

onMounted(() => {
  fetchData();
});

//数据添加相关
// 设置 formData 的初始值
const formData = ref({
  uuid: "",
  question: "",
  answer: "",
  dataSource: "",
  auditTime: "",
  auditUser: "",
  auditUserName: "",
  annotationRobot: "",
  auditRobot: "",
  assessRobot: "",
  peopleAuditResult: "",
  referenceDoc: "",
});

// 添加控制表单显示的状态变量
const showForm = ref(false);

// 切换表单显示状态的方法
const toggleForm = () => {
  showForm.value = !showForm.value;
};

// 修改 handleAdd 法
const handleAdd = async () => {
  try {
    formData.value.id = null;
    const token = localStorage.getItem("token");
    const response = await axios.post(
      "http://1.14.10.129:8081/system/annotation",
      formData.value,
      {
        headers: {
          Authorization: token,
        },
      }
    );

    // 显示成功消息
    ElMessage.success(response.data.msg);

    // 重置表单数据
    formData.value = {
      uuid: "",
      question: "",
      answer: "",
      dataSource: "",
      auditTime: "",
      auditUser: "",
      auditUserName: "",
      annotationRobot: "",
      auditRobot: "",
      assessRobot: "",
      peopleAuditResult: "",
      referenceDoc: "",
    };

    // 关闭表单
    showForm.value = false;

    // 重新获取数据
    fetchData();
  } catch (error) {
    ElMessage.error("添加数据失败：" + error.message);
  }
};

// 数据修改相关
const handleEdit = (row) => {
  console.log("当前行数据:", row);
  //打开表单
  showForm.value = true;
  //将当前行数据赋值给formData
  formData.value = row;
};

// 数据更新相关
const handleUpdate = async () => {
  try {
    const token = localStorage.getItem("token");
    const response = await axios.put(
      "http://1.14.10.129:8081/system/annotation",
      formData.value,
      {
        headers: {
          Authorization: token,
        },
      }
    );

    // 显示成功消息
    ElMessage.success(response.data.msg);

    // 重置表单数据
    formData.value = {
      uuid: "",
      question: "",
      answer: "",
      dataSource: "",
      auditTime: "",
      auditUser: "",
      auditUserName: "",
      annotationRobot: "",
      auditRobot: "",
      assessRobot: "",
      peopleAuditResult: "",
      referenceDoc: "",
    };

    // 关闭表单
    showForm.value = false;

    // 重新获取数据
    fetchData();
  } catch (error) {
    ElMessage.error("更新数据失败：" + error.message);
  }
};

// 添加删除方法
const handleDelete = async (row) => {
  try {
    // 显示确认对话框
    await ElMessageBox.confirm("确定要删除这条数据吗？", "警告", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    });

    const token = localStorage.getItem("token");
    const response = await axios.delete(
      `http://1.14.10.129:8081/system/annotation/${row.id}`,
      {
        headers: {
          Authorization: token,
        },
      }
    );

    ElMessage.success(response.data.msg || "删除成功");
    // 重新获取数据
    fetchData();
  } catch (error) {
    if (error === "cancel") {
      return;
    }
    ElMessage.error("删除失败：" + error.message);
  }
};

// 添加审核方法
const handleAudit = async (row, auditResult) => {
  try {
    const token = localStorage.getItem("token");
    // 创建更新数据对象
    const updateData = {
      ...row,
      peopleAuditResult: auditResult,
    };

    const response = await axios.put(
      "http://1.14.10.129:8081/system/annotation",
      updateData,
      {
        headers: {
          Authorization: token,
        },
      }
    );

    // 显示成功消息
    ElMessage.success(response.data.msg || "审核状态更新成功");

    // 重新获取数据
    fetchData();
  } catch (error) {
    ElMessage.error("审核状态更新失败：" + error.message);
  }
};

const vFocus = {
  mounted: (el) => {
    const textarea = el.querySelector("textarea");
    if (textarea) {
      textarea.focus();
      // 将光标移到文本末尾
      const len = textarea.value.length;
      textarea.setSelectionRange(len, len);
    }
  },
};

const startEdit = (row, field) => {
  // 关闭其他行的编辑状态
  tableData.value.forEach((item) => {
    item.isEditingQuestion = false;
    item.isEditingAnswer = false;
  });

  // 设置当前字段的编辑状态
  if (field === "question") {
    row.isEditingQuestion = true;
    row.originalQuestion = row.question;
  } else {
    row.isEditingAnswer = true;
    row.originalAnswer = row.answer;
  }

  // 使用 nextTick 确保 DOM 更新后再聚焦
  nextTick(() => {
    const textarea = document.querySelector(".edit-cell textarea");
    if (textarea) {
      textarea.focus();
      // 根据字段类型设置正确的值
      textarea.value = field === "question" ? row.question : row.answer;
    }
  });
};

const confirmEdit = async (row, field) => {
  // 防止重复触发
  if (!row.isEditingQuestion && !row.isEditingAnswer) return;

  // 如果内容没有变化，直接关闭编辑模式
  if (field === "question" && row.question === row.originalQuestion) {
    row.isEditingQuestion = false;
    return;
  } else if (field === "answer" && row.answer === row.originalAnswer) {
    row.isEditingAnswer = false;
    return;
  }

  try {
    const result = await ElMessageBox.confirm(
      "确认要修改这条数据吗？",
      "提示",
      {
        confirmButtonText: "是",
        cancelButtonText: "否",
        type: "warning",
        defaultButton: "confirm",
      }
    );

    if (result === "confirm") {
      formData.value = { ...row };
      await handleUpdate();
    } else {
      if (field === "question") {
        row.question = row.originalQuestion;
      } else {
        row.answer = row.originalAnswer;
      }
    }
  } catch {
    if (field === "question") {
      row.question = row.originalQuestion;
    } else {
      row.answer = row.originalAnswer;
    }
  } finally {
    if (field === "question") {
      row.isEditingQuestion = false;
    } else {
      row.isEditingAnswer = false;
    }
  }
};
</script>

<style scoped>
.data-add {
  padding: 20px;
}

.data-overview {
  padding: 20px;
}

.button-group {
  display: flex;
  justify-content: space-between;
  margin: 10px 0;
  padding: 0 20px;
}

.filter-buttons {
  display: flex;
  gap: 10px;
}

.button-container {
  display: flex;
  flex-direction: column;
  gap: 5px;
}

.button-row {
  display: flex;
  gap: 5px;
}

.button-row .el-button {
  padding: 4px 8px;
  font-size: 12px;
}

.ellipsis-cell {
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

:deep(.el-table) {
  --el-table-header-bg-color: #f5f7fa;
  --el-table-row-hover-bg-color: #f5f7fa;
  font-size: 13px;
}

.clickable {
  cursor: pointer;
}
.clickable:hover {
  background-color: #f5f7fa;
}
.edit-cell {
  padding: 0;
  margin: -8px;
  height: auto;
  min-height: 120px; /* 为文本框预留足够空间 */
}

.edit-cell :deep(.el-textarea__inner) {
  padding: 8px;
  resize: none;
  height: 100%;
  min-height: 100px;
  width: 100%;
}

/* 调整表格行高以适应编辑状态 */
:deep(.el-table__row) {
  transition: all 0.3s;
}
:deep(.el-table__row.editing-row) {
  height: auto !important;
  min-height: 120px;
}
</style>
